import {computed, reactive} from 'vue';
import {useStore} from 'vuex';

export default function getUserInfo(proxy) {
  // 用户基本信息
  const store = useStore();
  const userInfo = {
    userId: computed(() => store.state.userInfo.id)
  };
  ['username', 'isAdmin', 'role', 'token'].map(key => {
    userInfo[key] = computed(() => store.getters[key]);
  });

  // 用户导航配置
  const isOnlyNavTop = computed(() => store.state.isOnlyNavTop);
  const isOnlyNavLeft = computed(() => !store.state.isOnlyNavTop && store.state.isOnlyNavLeft);

  // 退出登录
  const logout = (msg = '凭证失效，请重新登录', type = 'error') => {
    msg && proxy.$message[type](msg);
    localStorage.clear();
    location.replace('/login');
  };

  // 用户-前端退出机制
  const operationTime = reactive({
    action: ['mousemove', 'keyup', 'click'],
    timeoutInterval: import.meta.env.VITE_TIMEOUT_INTERVAL * 60 * 1000,
    timeId: 0
  });
  const updateOperationTime = () => {
    if (operationTime.timeId) clearTimeout(operationTime.timeId);
    operationTime.timeId = setTimeout(() => {
      if (location.pathname !== '/login') logout('长时间未操作系统，请重新登录。');
      operationTime.timeId = 0;
    }, operationTime.timeoutInterval);
  };
  const addOperationListener = () =>
    operationTime.action.map(type => document.addEventListener(type, updateOperationTime));
  const removeOperationListener = () =>
    operationTime.action.map(type => document.removeEventListener(type, updateOperationTime));

  return {
    ...userInfo,
    isOnlyNavTop,
    isOnlyNavLeft,
    logout,
    addOperationListener,
    removeOperationListener
  };
}
